package com.study.cms.auth.service.impl;

import com.study.cms.auth.Dto.LoginDTO;
import com.study.cms.auth.service.LoginService;
import com.study.cms.basic.utils.BasicMap;
import com.study.cms.org.domain.Emp;
import com.study.cms.org.mapper.EmpMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private EmpMapper employeeMapper;

    @Override
    public Map<String, Object> login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        // 1 参数非空校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new RuntimeException("用户名和密码不能为空!请检查后重新提交!");
        }

        Emp employee = employeeMapper.loadByUsername(username);
        if (Objects.isNull(employee)) {
            throw new RuntimeException("用户名或密码错误!");
        }
        if (!password.equals(employee.getPassword())) {
            throw new RuntimeException("用户名或密码错误!");
        }

        String token = UUID.randomUUID().toString();
        BasicMap.loginMap.put(token, employee);

        // 将token和登录用户信息存入返回的map的对象中
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", token);


        employee.setPassword("");
        resultMap.put("loginUser", employee);    // 因为浏览器上要展示当前登录用户名
        return resultMap;
    }
}